// 这个文件专门存放关于列表的所有接口
const Router = require('koa-router')
const login = new Router()

const bodyparser = require('koa-bodyparser')
login.use(bodyparser()) // 调用中间件 就可以拿到前端post的数据

const jwt = require('jsonwebtoken')

const db = require('../utils/db.js')
const sm = require('../utils/smCrypto.js')

const qr = require('qr-image')
const { generateToken, verify } = require("../utils/websock/jwt");
const { sendData } = require("../utils/websock/ws");
const { getWss } = require("../utils/websock/index");

// 查询所有用户数据
login.post('/register', async (ctx) => {
  let body = ctx.request.body
  let name = body.account
  let password = body.pwd
  let tel = body.tel
  // 判断数据库有没有这个账号，有就登录，没有就添加注册一条
  let result = await new Promise((resolve, reject) => {
    let searchSql = `select * from user where name='${name}'`
    db.query(searchSql, (err, data) => {
      if (data.length > 0) {
        resolve(data)
      } else {
        resolve(false)
      }
    })
  })
  if (result) {
    // 能找到对应的账号 解密判断
    if (sm.decrypt(result[0].password) == sm.decrypt(password)) {
      // 账号密码正确，返回token
      ctx.body = {
        token: result[0],
        msg: '登录成功',
        username: name
      }
    } else {
      // 密码错误
      ctx.body = {
        msg: '密码错误',
        username: name
      }
    }
  } else {
    let res = await new Promise((resolve, reject) => {
      // 创建一个token expiresIn有效期
      let mytoken = jwt.sign({ 'name': name, 'mypwd': password }, 'secret', { expiresIn: 3600 })
      // 没有账号，要注册(插入数据)
      let searchSql = `insert into user (name, password, tel, token) values ('${name}', '${password}', '${tel}','${mytoken}')`
      db.query(searchSql, (err, data) => {
        if (err) throw err
        let obj = {
          msg: "注册成功",
          token: mytoken,
          username: name
        }
        resolve(obj)
      })
    })
    if (res) {
      ctx.body = res
    }
  }
})

// 通过 uuid 生成携带 uuid 的二维码
login.get("/login_qr_code/:uid", async (ctx) => {
  const uid = ctx.request.params.uid;
  // 对 uid 过期验证逻辑，略去
  const isExpired = false;

  if (!uid || isExpired) {
    ctx.body = {
      message: "二维码已过期"
    }
  } else {
    ctx.response.set('content-type', 'image/png');
    ctx.body = qr.image(uid, {
      size: 12,
      margin: 1
    });
  }
});

// 获取 TOKEN，这里就不考虑数据库、用户名/密码，略去手工登录操作
// 而是直接通过 fqmniu 这个 USER_ID 生成 TOKEN
login.get("/get_token", (ctx) => {
  const USER_ID = "fqniu";
  const token = generateToken(USER_ID);
  ctx.body = {
    message: "登录成功~",
    data: {
      token: token
    }
  }
});

// 登录及确认登录（模拟手机上的账号密码登录）
login.post("/login_by_code", async (ctx) => {
  // 用户的 token 来自手机端
  const token = ctx.request.body["token"];
  const tokenData = verify(token, "KEY");
  // codeId
  const uuid = ctx.request.body["uuid"];

  const wss = getWss();
  if (wss && wss.clients && tokenData) {
    // 可以在 wss.clients 中找到相应的客户端
    const clients = wss.clients;
    console.log(111, clients);

    // 找到对应的 ws 客户端
    let targetClient = [...clients].find((client) => client.loginCondition.uuid === uuid);
    if (targetClient) {
      if (targetClient.loginCondition.status === 0) {
        sendData(targetClient, "ok", {
          uuid: uuid,
          type: "SCANNED"
        });
        targetClient.loginCondition.status++;
        ctx.body = {
          message: "用户已经扫描了二维码，请点击确认按钮以确认登录"
        }
      } else if (targetClient.loginCondition.status === 1) {
        sendData(targetClient, "ok", {
          uuid: uuid,
          type: "SUCCESS",
          token: generateToken(tokenData.userId)
        });

        ctx.body = {
          message: "登录成功~"
        }

        targetClient.loginCondition.status++;
      } else {
        ctx.body = {
          message: "二维码已经失效！"
        }
      }
      return;
    }
  }
  ctx.body = {
    message: "登录失败"
  }
});


module.exports = login